package com.tungse.redisson;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.concurrent.CountDownLatch;

/**
 * @Author : Tungse
 * @Date: 2025/7/8 14:21
 * @Description:
 */
public class RLockTest {
    public static final RedissonClient redissonClient;
    static {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://localhost:6379")
                .setPassword("foobared");
        redissonClient = Redisson.create(config);
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        for (int idx = 0; idx < 2; idx++) {
            new Thread(() -> {
                RLock lock = redissonClient.getLock("TASK_LOCK:" + 10086);
                try {
//                    if (lock.tryLock(15, 30, TimeUnit.SECONDS)) {
                    if (lock.tryLock()) {
                        for (int i = 0; i < 10; i++) {
                            System.out.println(Thread.currentThread().getName() + "==" + i);
                            Thread.sleep(500);
                        }
                    }
                } catch (InterruptedException ignore) {
//                    ignore.printStackTrace();
                } finally {
                    if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                        lock.unlock();
                    }
                    countDownLatch.countDown(); // 确保无论如何都会执行countDown
                }
            }, "线程" + idx).start();
        }

        countDownLatch.await();
        System.out.println("执行完毕");
        redissonClient.shutdown();
    }
}
